//
//  DLCreateDataBaseVC.m
//  AllPass
//
//  Created by apple on 2021/11/1.
//

#import "DLCreateDataBaseVC.h"
#import "Kdb3Writer.h"
#import "Kdb4Writer.h"
@interface DLCreateDataBaseVC ()
@property (weak, nonatomic) IBOutlet UISegmentedControl *myseg;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topHeight;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *pswTF;
@property (weak, nonatomic) IBOutlet UITextField *rePswTF;

@end

@implementation DLCreateDataBaseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isHideNavBar = YES;
    self.isHideBottomLine = YES;
    self.view.backgroundColor = UnderLineColor;
    self.topHeight.constant = kStatusBarHeight + 20;
}
- (IBAction)doneBtnClick:(id)sender {
    if (self.nameTF.text.length == 0) {
        XHQHUDErrorText(NSLocalizedString(@"Please input database's name", nil));
        return;
    }
    if (self.pswTF.text.length == 0) {
        XHQHUDErrorText(NSLocalizedString(@"Please enter database's password", nil));
        return;
    }
    if (self.rePswTF.text.length == 0) {
        XHQHUDErrorText(NSLocalizedString(@"Please enter your password again", nil));
        return;
    }
    NSString *filename;
    if (self.myseg.selectedSegmentIndex == 0) {
        filename = [self.nameTF.text stringByAppendingPathExtension:@"kdb"];
    } else {
        filename = [self.nameTF.text stringByAppendingPathExtension:@"kdbx"];
    }
    
    NSString *documentsDirectory = [Mytools documentsDirectory];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:filename];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        XHQHUDErrorText(NSLocalizedString(@"A file already exists with this name", nil));
        return;
    }
    
    // Create the KdbWriter for the requested version
    id<KdbWriter> writer;
    if (self.myseg.selectedSegmentIndex == 0) {
        writer = [[Kdb3Writer alloc] init];
    } else {
        writer = [[Kdb4Writer alloc] init];
    }
    
    // Create the KdbPassword
    KdbPassword *kdbPassword = [[KdbPassword alloc] initWithPassword:self.pswTF.text
                                                    passwordEncoding:NSUTF8StringEncoding
                                                             keyFile:nil];
    
    [writer newFile:path withPassword:kdbPassword];
    if (self.createFinishBlock) {
        self.createFinishBlock();
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)backBtnClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)segClick:(UISegmentedControl *)sender {
}


@end
